package com.myweb;

import java.io.IOException;
import java.lang.Exception;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

@WebFilter("*.jsp")
public class MyWebFilter implements Filter {

  @PersistenceUnit
  private EntityManagerFactory emf;
  @Resource
  private UserTransaction utx;

  public MyWebFilter() {
  }

  @Override
  public void init(FilterConfig fConfig) throws ServletException {
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
      utx.begin();
      request.setAttribute(MyWeb.KEY_EM_FACTORY, emf);
      chain.doFilter(request, response);
      utx.commit();
    } catch (NotSupportedException | SystemException | IOException | ServletException 
            | HeuristicMixedException | HeuristicRollbackException |
            SecurityException | IllegalStateException e) {
      
      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
      try {
          utx.rollback();
      } catch (IllegalStateException | SecurityException | SystemException ex) {
        Logger.getLogger(MyWebFilter.class.getName()).log(Level.SEVERE, null, ex);
      }
    } catch (RollbackException rx){
      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rx.getCause().toString());
      try {
          utx.rollback();
      } catch (IllegalStateException | SecurityException | SystemException ex) {
        Logger.getLogger(MyWebFilter.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }

  @Override
  public void destroy() {
    if (emf != null && emf.isOpen()) {
      emf.close();
    }
  }
}
